//
//  GHMainViewController.swift
//  VerticalMotionShiftCalculator
//
//  Created by Apple on 2018/12/20.
//  Copyright © 2018年 guohao. All rights reserved.
//

import UIKit
import MBProgressHUD

class GHMainViewController: UIViewController, UITextFieldDelegate, GHSinglePickerViewDelegate {

    @IBOutlet weak var mainScrollView: UIScrollView!
    @IBOutlet weak var selectButton: UIButton!
    @IBOutlet weak var initialVerticalSpeedTextField: UITextField!
    @IBOutlet weak var gravityAccelerationTextField: UITextField!
    @IBOutlet weak var timeTextField: UITextField!
    @IBOutlet weak var distanceTextField: UITextField!
    
    var lastTextField: UITextField?
    var typeIndex: Int = 0
    
    var selectArray = ["Vertical throw distance (Δy)", "Initial vertical speed (Vy0)", "Gravity acceleration (g)", "Time (t)"]
    
    lazy var selectView: GHSinglePickerView = {
        
        let window = UIApplication.shared.keyWindow
        let _selectView = GHSinglePickerView.init(frame: (window?.bounds)!, data: selectArray)
        _selectView.delegate = self
        return _selectView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.lastTextField = distanceTextField
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if #available(iOS 11.0, *) {
            self.mainScrollView.contentInsetAdjustmentBehavior = .never
        }
    }
    
    
    func calculate() {
        
        var iv = self.initialVerticalSpeedTextField.text?.toFloat()
        var g = self.gravityAccelerationTextField.text?.toFloat()
        var t = self.timeTextField.text?.toFloat()
        var vdt = self.distanceTextField.text?.toFloat()
        
        if (typeIndex == 0) {
            vdt = round((iv! * t! - (0.5 * g! * t! * t!)) * 100) / 100
            self.distanceTextField.text = "\(vdt!)"
        } else if (typeIndex == 1) {
            iv = round(((vdt! + (0.5 * g! * t! * t!)) / t!) * 100) / 100
            self.initialVerticalSpeedTextField.text = "\(iv!)"
        } else if (typeIndex == 2) {
            g = round(((2 * (iv! * t! - vdt!)) / (t! * t!)) * 100) / 100
            self.gravityAccelerationTextField.text = "\(g!)"
        } else if (typeIndex == 3) {
            t = round((iv! + sqrt(iv! * iv! - (2 * g! * vdt!)) / g!) * 100) / 100
            self.timeTextField.text = "\(t! - 0.5)"
        }
    }
    
    
    // MARK: - IBAction
    
    @IBAction func selectAction(_ sender: UIButton) {
        
        if !(self.selectView.isDisplayedInScreen()) {       // 判断选择器是否显示在屏幕上，未显示则添加，显示则移除
            UIApplication.shared.keyWindow?.endEditing(true)
            let window = UIApplication.shared.keyWindow
            window?.addSubview(self.selectView)
            // 点击非选择区域关闭选择器
            let tap = UITapGestureRecognizer.init(target: self, action: #selector(cancelSelectAction))
            self.selectView.addGestureRecognizer(tap)
        } else {
            self.cancelSelectAction()
        }
    }
    
    @IBAction func calculateAction(_ sender: UIButton) {
        
        UIApplication.shared.keyWindow?.endEditing(true)
        
        var iv = self.initialVerticalSpeedTextField.text
        var g = self.gravityAccelerationTextField.text
        var t = self.timeTextField.text
        var vdt = self.distanceTextField.text
        
        if typeIndex == 0  {
            vdt = " "
        } else if typeIndex == 1 {
            iv = " "
        } else if typeIndex == 2 {
            g = " "
        } else if typeIndex == 3 {
            t = " "
        }
        
        if iv?.count == 0 || g?.count == 0 || t?.count == 0 || vdt?.count == 0 {
            MBProgressHUD.showError(error: "Please input all required feild")
            return
        }
        
        self.calculate()
    }
    
    
    // MARK: - GHSinglePickerViewDelegate
    
    func confirmAction(_ result: String) {
        self.cancelSelectAction()
        
        if result == self.selectButton.titleLabel?.text {
            return
        }
        
        self.lastTextField?.isEnabled = true
        self.selectButton.setTitle(result, for: .normal)
        let index = self.selectArray.index(of: result)
        typeIndex = index!
        if index == 0 {
            self.distanceTextField.isEnabled = false
            self.lastTextField = distanceTextField
        } else if index == 1 {
            self.initialVerticalSpeedTextField.isEnabled = false
            self.lastTextField = initialVerticalSpeedTextField
        } else if index == 2 {
            self.gravityAccelerationTextField.isEnabled = false
            self.lastTextField = gravityAccelerationTextField
        } else if index == 3 {
            self.timeTextField.isEnabled = false
            self.lastTextField = timeTextField
        }
        
        self.lastTextField?.text = ""
    }
    
    // 取消
    @objc func cancelSelectAction() {
        self.selectView.removeFromSuperview()   // 将选择器从父视图移除
    }
    
    
    // MARK: - UITextFieldDelegate
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        let length = string.count
        
        for loopIndex in 0..<length {   //只允许数字、+、-、.输入，ASCII：48~57、43、45、46
            let char = (string as NSString).character(at: loopIndex)
            if char == 43 || char == 45 || char == 46 {
                return true
            }
            if char < 48 {return false}
            if char > 57 {return false}
        }
        
        return true
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
